package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.pzhu.javaweb.pojo.FileMsg;
import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.service.FileService;
import cn.edu.pzhu.javaweb.service.imp.FileServiceImp;

/**
 * Servlet implementation class ShowFilesServlet
 */
@WebServlet("/showfiles")
public class ShowFilesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private FileService fileService = new FileServiceImp();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowFilesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取分页参数
        int page = 1, num = 10;
        String str_page = request.getParameter("page");
        try {
            page = Integer.parseInt(str_page);
        } catch (Exception e) {
            page = 1;
        }
        String str_num = request.getParameter("num");
        try {
            num = Integer.parseInt(str_num);
        } catch (Exception e) {
            num = 10;
        }
        
        // 获取分页数据
        Result<List<FileMsg>> page_result = fileService.showFilesByPages(page, num, 0);
        
        // 获取总记录数来计算总页数
        Result<List<FileMsg>> allResult = fileService.showFilesList();
        int totalRecords = allResult.getData() != null ? allResult.getData().size() : 0;
        int totalpage = (totalRecords - 1) / num + 1;
        
        // 将数据存储到request域中（使用转发而不是重定向）
        request.setAttribute("fileList", page_result.getData());
        request.setAttribute("currentPage", page);
        request.setAttribute("pageSize", num);
        request.setAttribute("totalPages", totalpage);
        request.setAttribute("totalRecords", totalRecords);
        
        // 使用转发到show.jsp（这样可以在request中保留数据）
        request.getRequestDispatcher("show.jsp").forward(request, response);
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
